﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

namespace updater
{
	public partial class MainForm : Form
	{
		private static string ReleasedZIPName = null;
		
		public MainForm()
		{
			InitializeComponent();
		}
		
		private void BackgroundWorker1DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
		{
			//kill the old hkgoldenhighlight.scr
			foreach (Process clsProcess in Process.GetProcesses()) {
				if (clsProcess.ProcessName.StartsWith("hkgoldenhighlight.scr"))
	            {
					clsProcess.Kill();
		        }
			}
			ReleasedZIPName = "hkgoldenhighlight-" + Program.newversion.Replace(".", "-") + ".zip";
			
			//download new executable file
			WebClient newvWebClient = new WebClient();
			string newvWebLink = "http://hkgoldenhighlight.googlecode.com/files/" + ReleasedZIPName;
			newvWebClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadFileProgressChange);
			newvWebClient.DownloadFileAsync(new Uri(newvWebLink), System.IO.Path.Combine(Application.StartupPath, ReleasedZIPName));
			newvWebClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.LocalDownloadedFilesProcess);
		}
		
		private void DownloadFileProgressChange(object sender, DownloadProgressChangedEventArgs e)
		{
			progressBar1.Value = Convert.ToInt32(e.ProgressPercentage * 0.9);
			label1.Text = "下載最新程式壓縮檔中（ " + e.TotalBytesToReceive / 1024 + "KB 中的 " + e.BytesReceived / 1024 + "KB ）……";
		}
		private void LocalDownloadedFilesProcess(object sender, AsyncCompletedEventArgs e)
		{
			//The zip file name must be formatted like: hkgoldenhighlight-1-0-3976-34851.zip
			label1.Text = "解壓縮檔案中……";
			#region License of ICSharpCode.SharpZipLib
			
			// http://www.icsharpcode.net/OpenSource/SharpZipLib/
			//
			// Linking this library statically or dynamically with other modules is
			// making a combined work based on this library.  Thus, the terms and
			// conditions of the GNU General Public License cover the whole
			// combination.
			// 
			// As a special exception, the copyright holders of this library give you
			// permission to link this library with independent modules to produce an
			// executable, regardless of the license terms of these independent
			// modules, and to copy and distribute the resulting executable under
			// terms of your choice, provided that you also meet, for each linked
			// independent module, the terms and conditions of the license of that
			// module.  An independent module is a module which is not derived from
			// or based on this library.  If you modify this library, you may extend
			// this exception to your version of the library, but you are not
			// obligated to do so.  If you do not wish to do so, delete this
			// exception statement from your version.
			
			#endregion
			FastZip fastzip = new FastZip();
			fastzip.ExtractZip(ReleasedZIPName, Application.StartupPath, "");
			progressBar1.Value = 95;
			label1.Text = "刪除壓縮檔";
			File.Delete(ReleasedZIPName);
			progressBar1.Value = 99;
			//load new executable and deleteupdater
			//http://stackoverflow.com/questions/2245201/how-can-i-make-my-net-application-erase-itself
			label1.Text = "程式即將結束。準備啟動 cmd 於此更新程式結束後移除檔案。";
			Thread.Sleep(2000);
			Process.Start("cmd.exe", "/C echo off & title 等候更新程式結束 & echo 等候更新程式結束 & ping 1.1.1.1 -n 1 -w 5000 > Nul & title 刪除更新程式 & echo 刪除更新程式 & Del /q \"" + Application.ExecutablePath + "\" & title 刪除解壓縮函式庫 & echo 刪除解壓縮函式庫 & Del /q \"" + System.IO.Path.Combine(Application.StartupPath, "ICSharpCode.SharpZipLib.dll") + "\"");
			progressBar1.Value = 100;
			Application.Exit();
		}
		
		private void MainFormLoad(object sender, EventArgs e)
		{
			backgroundWorker1.RunWorkerAsync();
		}
	}
}
